<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/2/12
 * Time: 12:39
 */
// 媒体管理后台
Class MediaAction extends CommonAction{
     // 首页
     Public function index(){
           $medialist = array();
           $condition['uid'] = _decrypt(cookie('loginId'));
           $medialist = D('media')->getMediaByMore($condition);
           $this->medialist = $medialist;
           $this->display();
     }

     // 添加
     Public function media_add(){
           $this->display();
     }

     Public function file_upload(){
          $file = $_FILES['fileToUpload'];
          if($file['error']==4){
                return 0;
          }
          $fileType = substr($file['name'],strrpos($file['name'],'.')+1);
          $mediaPath = "Data/Upload/media/";
          $uploadres = $this->_uploadfile($file,$mediaPath);
          $video = array("mp4",'MP4','avi','AVI');
          // 创建视频截图
          if(in_array($fileType,$video)){
             $mediaPath = "/".$uploadres['savepath'];
             $mediaPathShot = "/Data/Upload/media/shotScreen/";
             $result = $this->videoShotScreen($mediaPath,$mediaPathShot);
          }
          if($uploadres['code']==200){
              $res = array(
                   'code' => 200,
                   'name' => $uploadres['file'],
                   'savename' => $uploadres['savepath'],
              );
              if($result){
                    $res['screen'] = $result['shotScreenPath'];
              }
              print_r(json_encode($res));
          }
     }

    // 保存影音数据
    public function savemedia(){
         if(!IS_POST){
               echo "非法操作";
         }
        if(empty($this->_post('title'))){
               echo "标题不能为空";
        }
        $data['title'] = $this->_post('title');
        $data['name'] = $this->_post('name');
        $data['sort'] = $this->_post('sort');
        $data['keyword'] = $this->_post('keyword');
        $data['filepath'] = $this->_post('Filename');
        $data['type'] = $this->_post('type');
        $data['mtype'] = $this->_post('mtype')?1:0; // 0 音频  1 视频
        $data['intro'] = $this->_post('media_intro');
        $data['lrc'] = $this->_post('lrc');
        $data['uid'] = _decrypt(cookie('loginId'));
        if($this->_post('mediaScreen')){
            $data['fileScreen'] = $this->_post('mediaScreen');
        }
        $res = D("media")->addMedia($data);
        if($res){
            $this->show("success",U('admin/Media/Index'),'添加成功');
        }else{
            $this->show("error",U('admin/Media/media_add'),'添加失败');
        }
    }

    /**
     * 影音类别列表
     */
    public function media_type(){
         $Page = $_GET['page']?$_GET['page']:1;
         $pageSize = 10;
         $startLimit = ($Page-1)*$pageSize;
         $where['uid'] = cookie('loginId');
         $typeCount = M('media_type')->where($where)->count();
         $typeList = M('media_type')->where($where)->limit($startLimit,$pageSize)->select();
         if($typeCount>$pageSize){
                $url = "__URL__/media_type?";
                $pagestr = $this->page($typeCount,$Page,$pageSize,$url);
                $this->pagestr = $pagestr;
         }
         $this->typecount = $typeCount;
         $this->typelist = $typeList;
         $this->display();
    }

    /**
     * 添加类别列表
     */
    public function media_type_add(){
        if(IS_POST){
             $type = I('post.type_name');
             // 查询分类是否存在
             $where['name'] = $type;
             $res = M('media_type')->where($where)->find();
             if($res){
                 $this->show("error",U('admin/Media/media_type_add'),'该分类已存在');
                 die;
             }
             $inserData['name'] = $type;
             $inserData['uid']  = cookie('loginId');
             $inserData['created_at'] = time();
             if($_POST['id']){
                 $res = M('media_type')->where(array('id'=>$_POST['id']))->save($inserData);
                 $tips = "修改";
             } else {
                 $res = M('media_type')->add($inserData);
                 $tips = '添加';
             }
             if($res){
                 $this->show("success",U('admin/media/media_type'),'分类'.$tips.'成功');
             }else{
                 $this->show("error",U('admin/media/media_type'),'分类'.$tips.'失败');
             }
        }
        if($_GET['id']){
              $typeInfo = M('media_type')->find($_GET['id']);
              if(!$typeInfo){
                  $this->show("error",U('admin/media/media_type'),'分类信息错误');
              }
              $this->typeinfo = $typeInfo;
        }
        $this->display();
    }

    /**
     * 删除类别列表
     */
    public function media_type_del(){
        $id = $_GET['id'];
        $typeInfo = D('media_type')->find($id);
        $where['type'] = $typeInfo['name'];
        // 查询该类别内容是否为空
        $isEmpty = D('media')->getMediaByMore($where);
        if($isEmpty){
            $res = ['code'=>400,'msg'=>"请先删除该分类的内容"];
            echo json_encode($res);
            die;
        }
        $res = D('media_type')->delete($id);
        if(!$res){
            $res = ['code'=>200,'msg'=>"删除成功"];
            echo json_encode($res);
            die;
        }
        $res = ['code'=>200,'msg'=>"删除失败"];
        echo json_encode($res);
    }

    /**
     * 对上传的视频进行取帧截图
     * @param $mediaPath 视频路径（相对路径）
     * @param $mediashotScrren 截图保存路径（相对路径）
     */
     public function videoShotScreen($mediaPath,$mediashotScrren){
            // 首先将相对路径转换为绝对路径
            $root = substr(__FILE__,0,strpos(__FILE__,APP)+strlen(APP));
            $root = str_replace("\\",'/',$root);
            $mediaPath = $root.$mediaPath;
            $SaveShotScreen = $root.$mediashotScrren;
            if(!file_exists($mediaPath)||!is_dir($SaveShotScreen)){
                return;
            }
            $name = md5(date('YmdHis')).".png";
            $str = "ffmpeg -i ".$mediaPath." -y -f mjpeg -ss 3 -t 1 -s 740x500 ".$SaveShotScreen.$name;
            system($str);
            return(array("code"=>200,'shotScreenPath'=>$mediashotScrren.$name));
    }
}